
import { getMessagePageAPI } from "../../api/monitor"
import type { MessageItem } from "../../../typings/types/monitor/index"
import { messageLevelOption, judicialOption } from "../../api/constant"
import { Debtor } from "../../../typings/types/debtor";
import { formatDate, zcc } from "../../utils/util"
import { IAppOption } from "../../../typings";
import { goLogin } from "../../utils/request";
Page({
  // getTabBar 回调设置自定义tab-bar 高亮
  getInstance() {
    if (typeof this.getTabBar === 'function') {
      const tabBar = this.getTabBar();
      tabBar.setData({
        active: 1
      })
    }
  },
  // 展示时间选择器
  showPicker() {
    let start = this.data.dateStart;
    this.setData({
      dateVisible: true,
      current: 1,
      start,
      dateValue: start
    })
  },
  // 开始 结束时间选择切换
  currentSelect(e: any) {
    let current = e.currentTarget.dataset.current;
    if (current === 1 && this.data.start) {
      this.setData({
        dateValue: this.data.start
      })
    }
    if (current === 2 && this.data.end) {
      this.setData({
        dateValue: this.data.end
      })
    }
    this.setData({
      current
    })
  },
  // 日期选中值发生变化时触发
  onColumnChange(e: any) {
    if (this.data.current === 1) {
      this.setData({
        start: e.detail.value
      })
    } else {
      this.setData({
        end: e.detail.value
      })
    }

  },
  // 取消
  cancelbtn() {
    this.setData({
      start: "",
      dateStart: "",
      end: "",
      dateEnd: "",
      dateVisible: false
    })
    this.bindrefresherrefresh();
  },
  // 确认
  ensurebtn() {
    let start = this.data.start;
    let end = this.data.end;
    if (this.data.current === 1) {
      start = this.data.start || formatDate(this.data.defaultDate);
    }
    if (this.data.current === 2) {
      end = this.data.end || formatDate(this.data.defaultDate);
    }

    this.setData({
      dateStart: start,
      dateEnd: end,
      start,
      end,
    }, () => {
      if (this.data.start && this.data.end) {
        if (new Date(this.data.start) <= new Date(this.data.end)) {
          this.setData({
            dateVisible: false
          })
          this.bindrefresherrefresh()
        } else {
          wx.showToast({
            icon: "none",
            title: '开始时间不能大于结束时间',
          });
        }
      } else {
        this.setData({
          dateVisible: false
        })
        this.bindrefresherrefresh()
      }
    })
  },
  // ensurebtn() {
  //   if (this.data.start && this.data.end) {
  //     if (new Date(this.data.start) <= new Date(this.data.end)) {
  //       this.setData({
  //         dateStart: this.data.start,
  //         dateEnd: this.data.end,
  //         dateVisible: false
  //       })
  //       this.bindrefresherrefresh()
  //     } else {
  //       wx.showToast({
  //         icon: "none",
  //         title: '开始时间不能大于结束时间',
  //       });
  //     }
  //   } else {
  //     this.setData({
  //       dateStart: this.data.start,
  //       dateEnd: this.data.end,
  //       dateVisible: false
  //     })
  //     this.bindrefresherrefresh()
  //   }

  // },
  // 点击搜索
  searchFocus() {
    this.setData({
      searchInputClass: "input-is-focus",
      placeholderText: "请输入债务人企业名称",
    }, () => {
      this.setData({
        // keyWords: "",
        searchDisabled: false
      })
    })
  },
  // 收起
  searchBlur() {
    this.setData({
      searchInputClass: "",
      placeholderText: "搜索...",
      // keyWords: this.data.name,
      searchDisabled: true
    })
  },
  // 搜索框输入关键字
  searchChange(e: any) {
    console.log(this.data.keyWords)
    this.bindrefresherrefresh()
  },
  onChange(e: any) {
    console.log(e)
    const id = e.currentTarget.id
    const value = e.detail.value
    switch (id) {
      case "1":
        this.setData({
          messageLevel: value,
        })
        break
      case "2":
        this.setData({
          messageType: value,
        })
        break

      default: break
    }

    this.bindrefresherrefresh()
  },

  // // 风险等级筛选
  // messageLevelSelect() {
  //   if (this.data.cur.idName === 'messageLevelId' && this.data.visible) {
  //     this.setData({
  //       visible: false
  //     })
  //     return;
  //   }
  //   this.setData({
  //     cur: {
  //       idName: "messageLevelId",
  //       options: messageLevelOption,
  //       defaultValue: this.data.messageLevelValue,
  //       multiple: false
  //     }
  //   }, () => {
  //     this.setData({
  //       visible: true
  //     })
  //   })
  // },
  // // 线索类型筛选
  // typeSelect() {
  //   if (this.data.cur.idName === 'ptypeSelectorId' && this.data.visible) {
  //     this.setData({
  //       visible: false
  //     })
  //     return;
  //   }
  //   this.setData({
  //     cur: {
  //       idName: "ptypeSelectorId",
  //       options: this.data.ptypeOptions,
  //       defaultValue: this.data.ptypeValue,
  //       multiple: true
  //     }
  //   }, () => {
  //     this.setData({
  //       visible: true
  //     })
  //   })
  // },
  selectorChange(e: any) {
    // console.log(this.data.ptypeOptions, "ptypeOptions")
    // console.log(e.detail,"e.detail")
    console.log("e", e.currentTarget.dataset);

    // let id = e.currentTarget.dataset.id;
    // if (id === "messageLevelId") { //风险等级
    //   let ptypeValue = e.detail.map((item: any) => item.value);
    //   this.setData({
    //     messageLevel: e.detail,
    //     messageLevelValue: ptypeValue
    //   }, () => {
    //    this.getMonitorList()
    //   })
    // }
    // if (id === "utimeSelectorId") { // 时间筛选
    //   this.setData({
    //     utime: e.detail,
    //     utimeValue: [e.detail.value]
    //   })
    //   // this.getTypeList()
    // }
    // if (id === "searchCInputId") { // 企业搜索筛选
    //   this.setData({
    //     companyId: e.detail.value,
    //     companyName: e.detail.label,
    //     keyWords: e.detail.label
    //   })
    //   // this.getTypeList()
    // }
    // 更新线索列表
    // this.getList("reset");
  },
  // 更新swiperPages
  setSwiperPages() {
    let swiperPages = this.data.swiperPages;
    let ptypeValue = this.data.ptypeValue;
    // let isTotal = ptypeValue.length === this.data.typeItemTotal;
    // 如果 线索类型下拉框 全部不勾选的情况？？？？
    swiperPages.forEach((itemList, i) => {
      itemList.forEach((item, j) => {
        let index = ptypeValue.indexOf(item.type);
        let key = `swiperPages[${i}][${j}].checked`;
        if (index < 0) {
          this.setData({
            [key]: false
          })
        } else {
          this.setData({
            [key]: true
          })
        }
      })
    })
  },
  // 更新 ptypeOptions
  setPtypeOptions() {
    let ptypeOptions = this.data.ptypeOptions;
    let ptypeValue = this.data.ptypeValue;
    ptypeOptions.forEach((item, index) => {
      let key = `ptypeOptions[${index}].checked`;
      if (ptypeValue.indexOf(item.type) < 0) {
        this.setData({
          [key]: false
        })
      } else {
        this.setData({
          [key]: true
        })
      }
    })
  },
  // 获取线索类型列表
  getTypeList() {
    // type TypeItem = {
    //   type:string
    //   typeName: string
    //   typeDesc: string
    //   num: string
    // }
    this.setData({
      typeLoading: true
    })
    let dateInfo = this.data.utime.value === "all" ? "" : this.data.utime.value;
    let para = {
      id: this.data.companyId || "",
      dateInfo: dateInfo
    }
    getClueTypeListAPI(para).then((res: any) => {
      if (res.code === '000') {
        let totalNum = res.content.totalNum;
        let typeList = res.content.typeList;
        let ptypeValue = this.data.ptypeValue;
        let result: any[] = [];
        if (typeList && typeList.length > 0) {
          typeList.forEach((item: any) => {
            result.push(...item.typeList);
          })
        }
        result.filter((item) => {
          item.label = item.typeName;
          item.value = item.type;
          item.checked = ptypeValue.includes("item.type");
          return true;
        })
        result.unshift({
          num: res.content.totalNum,
          typeName: "全部线索类型",
          type: "all",
          label: "全部线索类型",
          value: "all",
          checked: ptypeValue.includes("all")
        })
        let ptypeOptions = result.slice();
        this.data.typeItemTotal = ptypeOptions.length;
        // 如果 swiperPages 不是空数组，？？？？
        let resultList = []; // [ [swiper-item], [swiper-item], [swiper-item]]
        let len = result.length;
        let itemNum = 9; // 每个swipterItem 展示的类型数量       
        let size = Math.ceil((len + 1) / itemNum);
        for (var i = 0; i < size; i++) {
          let index = i * itemNum;
          if ((index + itemNum) >= len) {
            resultList.push(result.slice(index))
          } else {
            resultList.push(result.slice(index, index + itemNum))
          }
        }
        // console.log(resultList, "resultList")
        this.setData({
          ptypeOptions: ptypeOptions,
          swiperPages: resultList,
          totalNum: totalNum,
        })
        this.setData({
          typeLoading: false
        })
      }
    })
  },
  getDataSlot() { },
  onSetting() {
    wx.navigateTo({ url: "/pages/monitor/components/setting/setting" })
  },
  // 消息监控列表
  getMonitorList() {
    this.setData({
      listLoading: true
    })
    let para = {
      page: this.data.page,
      perPage: this.data.perPage,
      startTime: this.data.dateStart && this.data.dateStart + " 00:00:00",
      endTime: this.data.dateEnd && this.data.dateEnd + " 23:59:59",
      messageLevel: this.data.messageLevel === 'all' ? '' : this.data.messageLevel,
      messageType: this.data.messageType === 'all' ? '' : this.data.messageType,
      companyName: this.data.keyWords,
    }
    return getMessagePageAPI(para).then((res: any) => {
      if (res.code === '000') {
        let content = res.content;
        let contentList = res.content.list || [];
        contentList.forEach((item: any) => {
          if (item.message) {
            item.message = JSON.parse(item.message)
          }
        })
        this.data.total = content.total;
        let monitorList = this.data.monitorList;
        this.setData({
          monitorList: monitorList.concat(contentList),
        })
      } else {

      }
    }).finally(() => {
      this.setData({
        listLoading: false
      })
    })
  },
  // 列表滾到到底
  scrollToLowerHandle() {
    if (this.data.total > this.data.monitorList.length) {
      this.data.page++;
      this.getMonitorList();
    }

  },
  // 數據重置
  reset() {
    this.data.page = 1;
    this.setData({
      monitorList: []
    })
  },
  // 下拉刷新
  async bindrefresherrefresh() {
    this.setData({
      refreshLoading: true
    })
    this.reset();
    await this.getMonitorList();
    this.setData({
      refreshLoading: false
    })
  },
  // levelChange(e: any) {
  //   this.setData({
  //     messageLevel: e.detail.value,
  //   });
  // },
  // typeChange(e: any) {
  //   this.setData({
  //     messageType: e.detail.value,
  //   });
  // },
  dateShow() {
    console.log("1111");

    this.setData({ visible: true })
  },

  /**
   * 页面的初始数据
   */
  data: {
    listLoading: false,
    refreshLoading: false,
    monitorList: [],
    companyName: "",
    page: 1,
    perPage: 10,
    total: 0,
    messageLevelOption: messageLevelOption,
    judicialOption: judicialOption,
    messageLevel: "",
    messageType: "",
    dateVisible: false,
    cur: {},
    visible: false,
    utime: { value: "", label: "" },
    utimeValue: ['all'],// 值数组
    utimeOptions: [
      { label: "全部", value: 'all' },
      { label: "近180天", value: '180' },
      { label: "近90天", value: '90' },
      { label: "近30天", value: '30' },
      { label: "近7天", value: '7' },
    ],
    // 线索类型
    ptype: [], // 选项数组 [{value:"", label:""}]
    ptypeValue: ["all"], // 值数组
    ptypeOptions: [
      // {label:"债权人代位权", value:"1", typeName:"",type:"",  num: 999, checked: false},
    ] as any,
    keyWords: "", //搜索企业关键字
    searchDisabled: true,
    typeItemTotal: 0,
    filter_level: {
      value: '',
      options: messageLevelOption
    },
    filter_type: {
      value: '',
      options: judicialOption
    },
    dateStart: "",
    dateEnd: "",
    defaultDate: Date.now(),
    dateValue: "",
    popupProps: {
      usingCustomNavbar: true,
    },
    start: "",
    end: "",
    current: 1, // 当前选择的时间代表开始时间1 结束时间 2
    dateStatus: 0,
    // 
    searchInputClass: '',
    placeholderText: '搜索...',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    if (getApp<IAppOption>().globalData.isLogin) {
      this.getInstance()
      this.getMonitorList()
    } else {
      zcc.logout()
      wx.showModal({
        title: "提示",
        content: "请登录",
        showCancel: false,
        success(res) {
          setTimeout(() => {
            wx.redirectTo({
              url: "/pages/login/login",
            });
          }, 800);
        },
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})
